﻿using B.S.DataBase.MyProject.Domain.RBAC;
using B.S.DataBase.MyProject.ErrorCode;
using B.S.DataBase.MyProject.Infrastructure.Interface;
using B.S.DataBase.MyWrite.API.Appicant.Command.Menus;
using MediatR;

namespace B.S.DataBase.MyWrite.API.Appicant.CommandHandler.Users
{
    public class AddRoleMenuCommandHandler : IRequestHandler<AddRoleMenuCommand, APIResult<object>>
    {

        private readonly IBaseRepository<RoleMenu> rmRep;

        public AddRoleMenuCommandHandler(IBaseRepository<RoleMenu> rmRep)
        {
            this.rmRep = rmRep;
        }

        public async Task<APIResult<object>> Handle(AddRoleMenuCommand request, CancellationToken cancellationToken)
        {
            APIResult<object> result = new APIResult<object>();
            //1.通过RoleId 角色ID查询所有数据批量删除
            var list = rmRep.GetAll().Result.Where(x => x.RoleId == request.RoleId).ToList();
            await rmRep.DeleteRemove(list);

            //2.通过list<>MenuId 批量添加
            var obj = request.MenuId.Select(x => new RoleMenu { MenuId = x, RoleId = request.RoleId }).ToList();
            var res = rmRep.AddRanges(obj).Result;
            result.Code = APIEnum.添加成功;
            result.Msg = APIEnum.添加成功.ToString();
            result.data = res.ToString();
            return await Task.FromResult(result);
        }
    }
}
